package com.sky.task;

import com.sky.constant.OrderStatistConstant;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 自定义定时任务类
 */
@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 订单超过15分钟未支付
     */
    @Scheduled(cron = "0 * * * * ? ")
    public void processTimeoutOrder() {
//          每搁一分钟查询超时的订单
        log.info("当前开始运行的时间:{}", LocalDateTime.now());
        Integer status = Orders.PENDING_PAYMENT;
        LocalDateTime time = LocalDateTime.now().minusMinutes(15);
        List<Orders> ordersList = orderMapper.selectTimeoutOrder(status, time);
        if (ordersList.size() != 0 && ordersList != null) {
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("商品超时未支付，订单自动取消");
                orders.setCancelTime(LocalDateTime.now());
                orderMapper.update(orders);
            }
        }
    }

    /**
     * 处于派送中状态
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void deliveryProgress() {
//        每日凌晨1点进行调用
        Integer status = Orders.TO_BE_CONFIRMED;
        LocalDateTime time = LocalDateTime.now().minusMinutes(60);
        List<Orders> ordersList = orderMapper.selectTimeoutOrder(status, time);
        if (ordersList.size() != 0 && ordersList != null) {
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.COMPLETED);
                orders.setCancelReason("派送中的订单长期为确认，已自动确认");
                orders.setCancelTime(LocalDateTime.now());
                orderMapper.update(orders);
            }
        }
    }
}
